﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using connector = Microsoft.Office.Server.Search.Connector;
using Microsoft.Office.Server.Search.Connector.BDC;
using Microsoft.BusinessData.MetadataModel;
using Microsoft.BusinessData.Runtime;
using MsExchangeBcsConnector.ExchangeBdcModel.Helpers;
using MsExchangeBcsConnector.ExchangeBdcModel;
using System.Web;

namespace MsExchangeBcsConnector
{
    class MsExchangeNamingContainer : INamingContainer
    {

        //GUID of the property set for the connector
        private static Guid propertySetGuid = new Guid("{3CC095F2-3010-4010-8B99-EDEFD1982F50}");

        private Uri sourceUri;
        private Uri accessUri;
        

        #region INamingContainer Members

            public void Initialize(Uri uri)
            {
                this.sourceUri = uri;
            }

            public Uri GetAccessUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance)
            {
                return this.GetAccessUri(entityInstance);
            }

            public Uri GetAccessUri(IEntityInstance entityInstance)
            {
                object[] ids = entityInstance.GetIdentity().GetIdentifierValues();
                string sAccessUri = string.Empty;
                // Is this a mailbox
                if (Constants.MailBoxEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                   
                    sAccessUri = this.sourceUri + string.Format("?{0}={1}", Constants.MailBoxEntityName, HttpUtility.UrlEncode(ids[0].ToString()));
                }
                // Is this a Mail folder
                else if (Constants.MailFolderEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                {

                    sAccessUri = this.sourceUri + string.Format("&{0}={1}",  Constants.MailFolderEntityName,Base32Url.ToBase32String(ids[0].ToString()));
                } 
                // Is this a mesage
                else if (Constants.MessageEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                {

                    sAccessUri = this.sourceUri + string.Format("&{0}={1}", Constants.MessageEntityName, Base32Url.ToBase32String(ids[0].ToString()));
                    /*sAccessUri = String.Format("{0}://{1}?{2}={3}&{4}={5}", Constants.SearchProtocolName, Constants.MessageEntityName, 
                        Constants.MessageEntityName, Base64.EncodeTo64(ids[0].ToString()),
                        Constants.MailBoxEntityName, HttpUtility.UrlEncode(ids[1].ToString()));*/
                } 
                // Is this an attachment
                else if (Constants.AttachmentEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    sAccessUri = this.sourceUri + string.Format("&{0}={1}", Constants.AttachmentEntityName, Base32Url.ToBase32String(ids[0].ToString()));
                   /* sAccessUri = String.Format("{0}://{1}?{2}={3}&{4}={5}&{6}={7}", Constants.SearchProtocolName, Constants.AttachmentEntityName,
                        Constants.AttachmentEntityName, HttpUtility.UrlEncode(ids[0].ToString()),
                        Constants.MessageEntityName, Base64.EncodeTo64(ids[1].ToString()),
                        Constants.MailBoxEntityName, HttpUtility.UrlEncode(ids[2].ToString()));*/
                    
                }
                else
                {
                    throw new NotImplementedException();
                }

                this.accessUri = new Uri(sAccessUri);
                
                return this.accessUri;
                
            }

            public Uri GetAccessUri(IEntity entity, ILobSystemInstance lobSystemInstance)
            {
                throw new NotImplementedException();
            }

            public Uri GetAccessUri(ILobSystemInstance lobSystemInstance)
            {
                throw new NotImplementedException();
            }

            public Uri GetAccessUri(ILobSystem lobSystem)
            {
                throw new NotImplementedException();
            }

            public Uri GetDisplayUri(IEntityInstance entityInstance, IEntityInstance parentEntityInstance)
            {
                return GetDisplayUri(entityInstance, String.Empty);
            }

            public Uri GetDisplayUri(IEntityInstance entityInstance, string computedDisplayUri)
            {
                if (string.IsNullOrEmpty(computedDisplayUri))
                    return this.sourceUri;
                return new Uri(computedDisplayUri);
          /*      /// ОШИБКА!
                object[] ids = entityInstance.GetIdentity().GetIdentifierValues();
                string sDisplayUri = string.Empty;
                //entityInstance.LobSystemInstance;
                if (string.IsNullOrEmpty(computedDisplayUri) && this.accessUri != null)
                    return this.accessUri;
                else if (!string.IsNullOrEmpty(computedDisplayUri))
                    return new Uri(computedDisplayUri); 
                else
                try
                {
                    if (Constants.MailBoxEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        sDisplayUri = BuildMailboxDisplayUrl(ids);
                    }
                    else if (Constants.MailFolderEntityName.Equals(entityInstance.Entity.Name, StringComparison.InvariantCultureIgnoreCase))
                    {
                        sDisplayUri = BuildMailFolderDisplayUrl(ids);
                    }
                    else
                    {
                        sDisplayUri = entityInstance["Url"] as string;
                    }
                }
                catch
                {
                   
                    sDisplayUri = String.Format("http://{0}",Guid.NewGuid().ToString());
                }

                return new Uri(sDisplayUri);*/
                
            }

            public Uri GetDisplayUri(IEntity entity, ILobSystemInstance lobSystemInstance)
            {
                return this.accessUri;
            }

            public Uri GetDisplayUri(ILobSystemInstance lobSystemInstance)
            {
                throw new NotImplementedException();
            }

            public Uri GetDisplayUri(ILobSystem lobSystem)
            {
                return this.accessUri;
            }



            public Guid PartitionId
            {
                get { return Guid.Empty; }
            }

            public Guid PropertySet
            {
                get { return propertySetGuid; }
            }

        

            /// <summary>
            /// Build URL to display MailBox based on entity parameters
            /// </summary>
            /// <param name="ids"></param>
            /// <returns></returns>
            private static string BuildMailboxDisplayUrl(object[] ids)
            {
               /*string MailboxDisplayPattern = LobSystemInstanceHelper.MailboxDisplayUrlPattern(lobSystemInstance);
               if (string.IsNullOrEmpty(MailboxDisplayPattern))
                   MailboxDisplayPattern = @"http://MailBox/_bdc/MsExchangeBcsConnector/?EMail={0}";
               return String.Format(MailboxDisplayPattern, HttpUtility.UrlEncode(ids[0] as string));*/
               return String.Format("{0}://{1}?{2}={3}", Constants.SearchProtocolName, Constants.MailBoxEntityName,
                       Constants.MailBoxEntityName, HttpUtility.UrlEncode(ids[0].ToString()));      
            }
        /// <summary>
            /// Build URL to display MailBox based on entity parameters
            /// </summary>
            /// <param name="ids"></param>
            /// <returns></returns>
            private static string BuildMailFolderDisplayUrl(object[] ids)
            {
              /* string MailFolderDisplayPattern = LobSystemInstanceHelper.GetPropertyValue(lobSystemInstance, Constants.MailFolderDisplayUrlPattern);
               if (string.IsNullOrEmpty(MailFolderDisplayPattern))
                   MailFolderDisplayPattern = @"http://MailFolder/_bdc/MsExchangeBcsConnector/?MailFolderID={0}EMail={1}";
               return String.Format(MailFolderDisplayPattern, HttpUtility.UrlEncode(ids[0] as string), HttpUtility.UrlEncode(ids[1] as string));*/
                return String.Format("{0}://{1}?{2}={3}", Constants.SearchProtocolName, Constants.MailBoxEntityName,
                       Constants.MailBoxEntityName, HttpUtility.UrlEncode(ids[0].ToString()));

            }

            /// <summary>
            /// Build URL to display Message based on entity parameters
            /// </summary>
            /// <param name="ids"></param>
            /// <returns></returns>
            private static string BuildMessageDisplayUrl(object[] ids, ILobSystemInstance lobSystemInstance)
            {
                string MailboxDisplayPattern = LobSystemInstanceHelper.MessageDisplayUrlPattern(lobSystemInstance);
                return String.Format(MailboxDisplayPattern, ids[0], ids[1]);
            }


        #endregion
    }
}
